/**
 * 病历本字
 */

import React, {Component} from 'react';
import {
  View,
  TextInput,
  Text,
  StyleSheet,
  Dimensions,
  Button,
  Image,
  ScrollView,
  TouchableOpacity,
  FlatList,
  ActivityIndicator,
  Alert,
} from 'react-native';
import Case from '../components/Case';
import {HeaderLeft} from '../../components';
import {diseaseHistoryList, deleteDiseaseHistory} from '../../api/index';
import {setCaseBook, setToastMsg} from '../../actions/index';
import {connect} from 'react-redux';
import RefreshListView, {RefreshState} from 'react-native-refresh-list-view';

const {width} = Dimensions.get('window');

class CaseBook extends Component {
  static refVar;
  constructor(props) {
    super(props);
    this.state = {
      result: [],
      refresh: false,
      refreshState: RefreshState.Idle,
      currentPage: 1,
    };

    CaseBook.refVar = this;
  }
  static navigationOptions = ({navigation}) => ({
    headerTitle: '爱心病历本',
    headerStyle: {
      backgroundColor: '#fff',
      borderBottomWidth: 0,
      height: 44,
      elevation: 0,
    },
    headerTitleStyle: {
      flex: 1,
      textAlign: 'center',
      color: '#333',
      fontSize: 17,
      fontWeight: '400',
    },
    headerLeft: <HeaderLeft triggerBack={() => navigation.goBack()} />,
    headerRight: (
      <TouchableOpacity
        style={{marginRight: 10}}
        onPress={() => {
          navigation.navigate('AddCase', {
            callback: data => CaseBook.refVar.addCaseToArr(data),
          });
        }}>
        <Text style={{fontSize: 30, color: '#00AEFF'}}>+</Text>
      </TouchableOpacity>
    ),
  });

  addCaseToArr(data) {
    console.log('准备回调函数');
    console.log(data);
    this.state.result.push(data);
  }
  async getCase() {
    let result = await diseaseHistoryList({pageNo: 1, pageSize: 5});
    this.setState({
      result: result.data,
    });
    this.props.setCaseBook({caseBook: result.data});
  }
  componentDidMount(): void {
    this.getCase();
  }
  removeFunc(index) {
    Alert.alert('删除病例', '确定删除吗？', [
      {text: ''},
      {text: '再想想'},
      {
        text: '确认删除',
        onPress: () => this.confirm(index),
      },
    ]);
  }
  async confirm(index) {
    let data = this.state.result;
    let result = await deleteDiseaseHistory({id: data[index].id});
    if (result.error_code === 0 || result.error_code === '0') {
      this.props.setToastMsg('删除成功!');
      data.splice(index, 1);
      this.setState({
        refresh: !this.state.refresh,
      });
      //this.props.setCaseBook({caseBook: this.state.result.data});
    } else {
      this.props.setToastMsg('删除失败!');
    }
  }
  addCase(data) {
    this.state.result.push(data);
    this.setState({
      refresh: !this.state.refresh,
    });
  }
  async onHeaderRefresh() {
    this.setState({
      refreshState: RefreshState.HeaderRefreshing,
      currentPage: 1,
    });
    let result = await diseaseHistoryList({pageNo: 1, pageSize: 5});
    this.setState({
      result: result.data,
      refresh: !this.state.refresh,
    });
    this.setState({refreshState: RefreshState.Idle});
  }
  async onFooterRefresh() {
    this.setState({refreshState: RefreshState.FooterRefreshing});
    let pageResult = [];
    try {
      pageResult = await diseaseHistoryList({
        pageNo: ++this.state.currentPage,
        pageSize: 5,
      });
    } catch (e) {
      this.props.setToastMsg('到底啦！');
      this.setState({refreshState: RefreshState.Idle});
    }
    let result = [...this.state.result, ...pageResult.data];
    this.setState({result: result, refresh: !this.state.refresh});
    this.setState({refreshState: RefreshState.Idle});
  }
  render() {
    const results = {
      data: [
        {
          disease: '感冒',
          description: '感冒难受死了',
          id: 1,
          time: 1567382400000,
          title: '感冒发烧123',
          hospital: '燕大医院',
          pictures:
            '["https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1568997444682&di=aedd401aaec7f02f87d2f9fd6f51eaaf&imgtype=0&src=http%3A%2F%2Fpic2.cxtuku.com%2F00%2F06%2F73%2Fb4019e49855e.jpg"]',
        },
        {
          disease: 'undefined',
          description: 'undefined',
          id: 3,
          time: 907286400000,
          title: '兔兔',
          hospital: '哦哦哦',
          pictures: 'undefined',
        },
        {
          description: '有点发烧',
          id: 4,
          time: 907286400000,
          title: '123',
          hospital: '燕大医院',
        },
      ],
      error_code: 0,
    };
    return (
      <RefreshListView
        data={this.state.result}
        refreshState={this.state.refreshState}
        onHeaderRefresh={() => this.onHeaderRefresh()}
        onFooterRefresh={() => this.onFooterRefresh()}
        renderItem={({item, index}) => (
          <View>
            <Case
              url={item.pictures}
              disease={item.disease}
              description={item.description}
              time={item.time}
              title={item.title}
              hospital={item.hospital}
              pics={item.pictures}
              navFunc={() =>
                this.props.navigation.navigate('EditCase', {
                  id: item.id,
                  callback: data => this.addCase(data),
                })
              }
              deleteFunc={() => this.removeFunc(index)}
            />
          </View>
        )}
      />
    );
  }
}
export default connect(
  state => ({
    caseBook: state.home.caseBook,
  }),
  dispatch => ({
    setCaseBook: data => dispatch(setCaseBook(data)),
    setToastMsg: text => dispatch(setToastMsg(text)),
  }),
)(CaseBook);
